<template>
  <div class="titbox">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="门店名称" label-width="150px" prop="store_name">
        <el-input style="width:98%;" v-model="ruleForm.store_name"></el-input>
      </el-form-item>
      <el-form-item label="座位类别" label-width="150px" prop="type">
        <el-select v-model="ruleForm.type" style="width:50%" multiple placeholder="请选择">
          <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" label-width="150px" prop="phone">
        <el-input style="width:98%;" v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="营业时间" label-width="150px" required>
        <el-time-picker
              is-range
              v-model="startTime1"
              format="HH:mm"
              value-format="HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
        <!-- <div style="display:flex">
          <div>
            <el-form-item prop="start_time">
              <el-time-select
                placeholder="选择时间"
                v-model="ruleForm.start_time"
                :picker-options="{
                      start: '00:00',
                      step: '00:30',
                      end: '24:00',
                      maxTime: ruleForm.end_time
                    }"
              ></el-time-select>
            </el-form-item>
          </div>
          <div style="margin-left:20px;margin-right:20px">-</div>
          <div>
            <el-form-item prop="end_time">
              <el-time-select
                placeholder="选择时间"
                v-model="ruleForm.end_time"
                :picker-options="{
                      start: '00:00',
                      step: '00:30',
                      end: '24:00',
                      minTime: ruleForm.start_time
                    }"
              ></el-time-select>
            </el-form-item>
          </div>
        </div> -->

        <!-- </el-col> -->
      </el-form-item>
      <!-- <el-form-item label="休息日" label-width="150px" prop="restday">
              <div class="inpts">
                <span style="cursor: pointer;" @click="installdate">设置休息日</span>
              </div>
      </el-form-item>-->
      <!-- <el-form-item label="座位解锁时间" label-width="150px" prop="unlock_time">
        <el-time-select
          v-model="ruleForm.unlock_time"
          style="width:98%"
          :picker-options="{
    start: '00:00',
    step: '00:30',
    end: '24:00'
  }"
          placeholder="选择时间"
        ></el-time-select>
      </el-form-item> -->
      <!-- <el-form-item label="选座时间颗粒度" label-width="150px" prop="choose_time">
        <el-input placeholder="请输入时间值" style="width:98%" v-model="ruleForm.choose_time">
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item> -->
      <el-form-item label="门店地址" label-width="150px" prop="address">
        <el-input style="width:98%" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="开门距离" label-width="150px" prop="distance">
        <el-input placeholder="请输入开门距离" style="width:98%" v-model="ruleForm.distance">
          <template slot="append">米</template>
        </el-input>
      </el-form-item>
      <el-form-item label="Wi-Fi 信息" label-width="150px">
        <div style="display:flex">
          <div>

        <!-- <el-col :span="10"> -->
        <el-form-item prop="wifi_name">
          <el-input placeholder="请输入Wi-Fi名称" v-model="ruleForm.wifi_name"></el-input>
        </el-form-item>
        </div>
        <div style="margin-left:20px;margin-right:20px">-</div>
        <!-- </el-col> -->
        <!-- <el-col class="line" :span="1">-</el-col> -->
        <!-- <el-col :span="10"> -->
        <div>
              <el-form-item prop="wifi_code">
          <el-input placeholder="请输入Wi-Fi密码" v-model="ruleForm.wifi_code"></el-input>
        </el-form-item>
        </div>
    
        </div>

        <!-- </el-col> -->
      </el-form-item>
      <!-- <el-form-item label="客服微信" label-width="150px" prop="wx_code">
          <el-input style="width:98%;" placeholder="请输入客服微信" v-model="ruleForm.wx_code"></el-input>
      </el-form-item> -->
      <el-form-item label="客服链接" label-width="150px" prop="wechat_link">
          <el-input style="width:98%;" placeholder="请输入客服链接" v-model="ruleForm.wechat_link"></el-input>
      </el-form-item>
      <el-form-item label="设备设施" label-width="150px" prop="facility_id">
        <el-select v-model="ruleForm.facility_id" style="width:50%" multiple placeholder="请选择">
          <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="到店指引" label-width="150px" prop="guide">
        <el-button
          type="warning"
          size="mini"
          style="display:inline-block;margin-right:10px;"
          @click="lookimg"
        >查看指引图片</el-button>
        <el-upload
          style="display:inline-block"
          action="https://m.sapiki.com//admin/common/imageUpload"
          :show-file-list="false"
          :on-success="handlestore"
          :before-upload="beforeAvatarUpload"
        >
          <el-button size="mini" type="primary">上传指引图片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-dialog title="到店指引图片" :visible.sync="lookpopup" width="50%">
      <div style="text-align:center">
        <el-image style="width: 376px; height: 668px" :src="storeimageUrl" :fit="fit"></el-image>
      </div>
    </el-dialog>
    <!-- <Map @addressInfo="getAddress" /> -->
    <div id="container" class="mapbox"></div>
    <el-button
      type="primary"
      size="mini"
      style="float:right;margin-right:20px;margin-bottom:40px;margin-top:40px"
      @click="saveformdata('ruleForm')"
    >添加</el-button>
  </div>
</template>
<script>
var searchService,
  geocoder,
  map,
  markersArray = [];
import { storeAdd, returnStore } from "@/api/user";
import Base64 from "@/utils/base";
export default {
  data() {
    return {
      startTime1: ['00:00','23:59'],
      // startTime:"",
      // endTime: "",
      lookpopup: false,
      ruleForm: {
        store_name: "",
        address: "",
        phone: "",
        distance:"",
        wifi_name:"",
        wifi_code:"",
        // wx_code:"",
        wechat_link:"",
        facility_id:""
      },
      options1: "",
      options: "",
      rules: {
        store_name: [
          {
            required: true,
            message: "请输入门店名称",
            trigger: "blur"
          }
        ],
        type: [
          {
            required: true,
            message: "请选择座位类别",
            trigger: "blur"
          }
        ],
        address: [
          {
            required: true,
            message: "请输入门店地址",
            trigger: "change"
          }
        ]
      },
      coordinate: {
        lat: "",
        lng: ""
      },
      storeimageUrl: ""
    };
  },
  created() {
    this.getcheckdata();
    this.getip();
  },
  methods: {
    // changetabs(e){
      // console.log(e)
      // this.startTime = e[0]
      // this.endTime = e[1]
    // },
    // 中国标准时间 转换成 年月日
    getSimpleDate(date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var s = date.getSeconds();
      s = s < 10 ? '0' + s : s;
      return h + ':' + minute
    },
    // 根据IP获取坐标
    getip() {
      this.$jsonp("https://apis.map.qq.com/ws/location/v1/ip", {
        key: "M6DBZ-QDQKU-OV3VS-2HEJJ-UMTXZ-NTBY3",
        output: "jsonp"
      })
        .then(res => {
          if (res.status === 0) {
            // 获取到的经纬度处理
            this.coordinate.lat = parseFloat(res.result.location.lat).toFixed(
              6
            );
            this.coordinate.lng = parseFloat(res.result.location.lng).toFixed(
              6
            );
            // 获取到IP经纬度，在渲染地图（一种做法）
            this.init();
          }
        })
        .catch(e => {});
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
        return;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return;
      }
    },
    handlestore(res, file) {
      this.storeimageUrl = res.file_path;
    },
    //查看指引图片
    lookimg() {
      this.lookpopup = true;
    },
    init() {
      //步骤：定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
      //设置地图中心点
      var myLatlng = new qq.maps.LatLng(
        this.coordinate.lat,
        this.coordinate.lng
      );
      //定义工厂模式函数
      var myOptions = {
        zoom: 13, //设置地图缩放级别
        center: myLatlng, //设置中心点样式
        mapTypeId: qq.maps.MapTypeId.ROADMAP //设置地图样式详情参见MapType
      };
      //获取dom元素添加地图信息
      var map = new qq.maps.Map(
        document.getElementById("container"),
        myOptions
      );
      //给地图添加点击事件
      //并获取鼠标点击的经纬度
      let that = this;
      let marker = "";
      marker = new qq.maps.Marker({
        position: myLatlng,
        map: map
      });
      qq.maps.event.addListener(map, "click", function(event) {
        if (!marker) {
          marker = new qq.maps.Marker({
            position: event.latLng,
            map: map
          });
          return;
        }
        marker.setPosition(event.latLng);
        that.coordinate.lat = event.latLng.getLat();
        that.coordinate.lng = event.latLng.getLng();
        that.getaddressinfo(event.latLng.getLat(), event.latLng.getLng());
      });
    },
    //获取详细地址
    getaddressinfo(lat, lng) {
      this.$jsonp("https://apis.map.qq.com/ws/geocoder/v1/?", {
        location: `${lat},${lng}`, // 经纬度
        key: "M6DBZ-QDQKU-OV3VS-2HEJJ-UMTXZ-NTBY3",
        output: "jsonp" // output必须jsonp   不然会超时
      }).then(res => {
        this.ruleForm.address = res.result.formatted_addresses.recommend;
        // this.areaCode = res.result.ad_info.adcode;
      });
    },
    //添加
    saveformdata(formName) {
      if(this.startTime1==null){
        this.$message({
            message:"请选择营业时间",
            type:'warning'
          })
        return
      }
      if(this.ruleForm.wechat_link==""){
        this.$message({
            message:"请输入客服链接",
            type:'warning'
          })
        return
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          storeAdd({
            request_data: Base64.encode(
              JSON.stringify({
                // store_id: JSON.parse(localStorage.getItem("storemenu"))[0].id,
                store_name: this.ruleForm.store_name,
                type: this.ruleForm.type.join(","),
                phone: this.ruleForm.phone,
                // start_time: this.ruleForm.start_time,
                // end_time: this.ruleForm.end_time,
                start_time: this.startTime1[0],
                end_time: this.startTime1[1],
                rest_time: "",
                temp_start_time: "",
                temp_end_time: "",
                unlock_time: "",
                choose_time: "",
                address: this.ruleForm.address,
                distance: this.ruleForm.distance,
                wifi_name: this.ruleForm.wifi_name,
                wifi_code: this.ruleForm.wifi_code,
                // wx_code: this.ruleForm.wx_code,
                wechat_link:this.ruleForm.wechat_link,
                wx_image: "",
                facility_id: this.ruleForm.facility_id.join(","),
                guide_image: this.storeimageUrl,
                // facility: this.ruleForm.facility_id,
                lng: this.coordinate.lng,
                lat: this.coordinate.lat
              })
            )
          }).then(res => {
            if(res.status==2){
          this.$message({
            message:res.message,
            type:'warning'
          })
          return
        }
            this.$router.push({ path: "/admin/store/storeList" });
          });
        } else {
          return false;
        }
      });
    },
    //下拉数据
    getcheckdata() {
      returnStore({}).then(res => {
        this.options1 = res.result.fac;
        this.options = res.result.gen;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.titbox {
  width: 100%;
  margin-top: 20px;
}
.mapbox {
  width: 98%;
  margin: 0 auto;
  height: 400px;
}
</style>